package com.jxm.security.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import com.jxm.security.entity.User;
import lombok.Data;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2022/5/24 21:54
 * @Version: 1.0
 */
@Data
@ToString
public class SysUser implements UserDetails,Serializable {

    private User user;

    private List<String> permissions;

    public SysUser(){

    }

    public SysUser(User user,List<String> permissions){
        this.user = user;
        this.permissions = permissions;
    }

    public SysUser(User user){
        this.user = user;
    }

    @JSONField(serialize = false) //不需要序列化（因为GrantedAuthority序列化到redis出现问题）
    private Collection<GrantedAuthority> authorities = new ArrayList<>();;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(!ObjectUtils.isEmpty(authorities)){ //只需要转换一次
            return authorities;
        }
        if(!ObjectUtils.isEmpty(permissions) && permissions.size() > 0){
            for (String permission : permissions) {
                if(StringUtils.hasLength(permission)){
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
                    authorities.add(authority);
                }
            }

        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
